<template>
  <el-drawer :close-on-click-modal="false" :close-on-press-escape="false"
             :title="!dataForm.id ? $t('add') : $t('update')" align-center v-model="visible" size="60%">
    <el-form :model="dataForm" :rules="rules" @keyup.enter="dataFormSubmitHandle()" label-width="120px"
             ref="dataFormRef">
      <el-row>
        <el-col :span="24">
          <el-form-item label="标题" prop="title">
            <el-input maxlength="50" placeholder="标题" show-word-limit v-model="dataForm.title"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="排序" prop="sort">
            <el-input-number v-model="dataForm.sort" :min="0"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="正文类型" prop="textType">
            <ren-radio-group dict-type="notice_text_type" v-model="dataForm.textType"></ren-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item class="myUEditorClass" label="富文本" prop="textContent" v-show="dataForm.textType == 0">
            <div style="width: 100%; margin-bottom: 16px">
              <el-button @click="getFich" type="primary" style="float: right">获取公众号文章</el-button>
            </div>
            <UEditor v-model:html="dataForm.textContent"></UEditor>
          </el-form-item>
          <el-form-item label="视频" prop="videoContent" v-show="dataForm.textType == 1">
            <FileUpload v-model:ossPath="dataForm.videoContent.url" v-model:ossName="dataForm.videoContent.name"
                        accept="video/*" fileType="视频" :limit="1" :multiple="false"></FileUpload>
          </el-form-item>

          <el-form-item label="PDF" prop="pdfContent" v-show="dataForm.textType == 2">
            <FileUpload v-model:ossPath="dataForm.pdfContent.url" v-model:ossName="dataForm.pdfContent.name"
                        accept="application/pdf" fileType="PDF" :limit="1" :multiple="false"></FileUpload>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="24">
          <el-form-item label="简述" prop="description">
            <el-input clearable maxlength="300" placeholder="请填写简述" rows="4" type="textarea"
                      v-model="dataForm.description"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="地址" prop="address">
            <el-input placeholder="请填写地址" v-model="dataForm.address"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="预览图片" prop="image" v-if="!loading">
            <single-upload v-model="dataForm.image" :update="addKey"></single-upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template v-slot:footer>
      <el-button @click="visible = false">{{ $t("cancel") }}</el-button>
      <el-button @click="dataFormSubmitHandle()" type="primary">{{ $t("confirm") }}</el-button>
    </template>
    <el-dialog v-model="dialogVisible" width="30%" title="获取微信公众号文章">
      <el-form :model="dataForm2" :rules="rules2" ref="dataForm2Ref">
        <el-form-item label="文章链接" prop="url">
          <el-input v-model="dataForm2.url"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="getText"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
  </el-drawer>
</template>

<script lang="ts" setup>
import {reactive, ref, watch} from "vue";
import baseService from "@/service/baseService";
import SingleUpload from "@/components/jiuse/single-upload/index.vue";
import FileUpload from "@/components/jiuse/file-upload/index.vue";
import {useI18n} from "vue-i18n";
import {ElMessage, ElNotification} from "element-plus";
import UEditor from "@/components/UEditor/index.vue";

const {t} = useI18n();
const emit = defineEmits(["refreshDataList"]);

const visible = ref(false);
const loading = ref(true);
const dataFormRef = ref();
const dataForm2Ref = ref();
const dialogVisible = ref(false);
const addKey = ref(0);

const dataForm = reactive({
  id: "",
  type: "",
  title: "",
  textType: 0,
  textContent: "",
  videoContent: {
    url: "",
    name: ""
  },
  pdfContent: {
    url: "",
    name: ""
  },
  description: "",
  address: "",
  image: "",
  sort: 0,
  isPublish: 0,
  isTopped: 0,
  creator: "",
  createDate: "",
  updater: "",
  updateDate: ""
});

const dataForm2 = reactive({
  url: ""
});

const rules2 = ref({
  url: [{required: true, message: "请输入链接", trigger: "blur"}]
});

const rules = ref({
  title: [{required: true, message: "请输入标题", trigger: "blur"}],
  sort: [{required: true, message: "请选择排序", trigger: "change"}],
  textType: [{required: true, message: "请选择正文类型", trigger: "change"}],
  textContent: [{required: true, message: "请填写富文本内容", trigger: "change"}]
});

watch(
  () => dataForm.textType,
  (newVal, oldVal) => {
    if (newVal == 0) {
      rules.value = {
        title: [{required: true, message: "请输入标题", trigger: "blur"}],
        sort: [{required: true, message: "请选择排序", trigger: "change"}],
        textType: [{required: true, message: "请选择正文类型", trigger: "change"}],
        textContent: [{required: true, message: "请填写富文本内容", trigger: "change"}]
      };
    } else {
      rules.value = {
        title: [{required: true, message: "请输入标题", trigger: "blur"}],
        sort: [{required: true, message: "请选择排序", trigger: "change"}],
        textType: [{required: true, message: "请选择正文类型", trigger: "change"}]
      } as any;
    }
  }
);

interface ParamsProps {
  id: number;
  type: string;
}

const init = (params: ParamsProps) => {
  visible.value = true;
  dataForm.id = "";
  dataForm.type = params.type;

  // 重置表单数据
  if (dataFormRef.value) {
    dataFormRef.value.resetFields();
  }

  if (params.id) {
    getInfo(params.id);
  } else {
    dataForm.image = "";
    addKey.value++;
    loading.value = false;
  }
};

const getFich = () => {
  dialogVisible.value = true;
};

const getText = () => {
  dataForm2Ref.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    baseService.post("/bus/busnotice/getRichTextByUrl", dataForm2).then((res) => {
      dataForm.textContent = res.data;
      dialogVisible.value = false;
    });
  });
};

// 获取信息
const getInfo = (id: number) => {
  baseService
    .get("/bus/busnotice/" + id)
    .then((res) => {
      Object.assign(dataForm, res.data);
      if (dataForm.videoContent) {
        // @ts-ignore
        let videoContent = JSON.parse(dataForm.videoContent);
        dataForm.videoContent = {
          url: videoContent.url,
          name: videoContent.name
        };
      } else {
        dataForm.videoContent = {
          url: "",
          name: ""
        };
      }
      if (dataForm.pdfContent) {
        // @ts-ignore
        let pdfContent = JSON.parse(dataForm.pdfContent);
        dataForm.pdfContent = {
          url: pdfContent.url,
          name: pdfContent.name
        };
      } else {
        dataForm.pdfContent = {
          url: "",
          name: ""
        };
      }
    })
    .finally(() => {
      addKey.value++;
      loading.value = false;
    });
};

// 表单提交
const dataFormSubmitHandle = () => {
  dataFormRef.value.validate((valid: boolean) => {
    if (!valid) {
      return false;
    }
    if (dataForm.textType == 1 && !dataForm.videoContent.url) {
      ElNotification({
        title: "温馨提示",
        message: "请上传视频！",
        type: "warning"
      });
      return false;
    } else if (dataForm.textType == 2 && !dataForm.pdfContent.url) {
      ElNotification({
        title: "温馨提示",
        message: "请上传PDF！",
        type: "warning"
      });
      return false;
    } else if (dataForm.textType == 3 && !dataForm.image) {
      ElNotification({
        title: "温馨提示",
        message: "请上传预览图片！",
        type: "warning"
      });
      return false;
    }
    if (dataForm.videoContent.url) {
      // @ts-ignore
      dataForm.videoContent = JSON.stringify(dataForm.videoContent);
      // @ts-ignore
      dataForm.pdfContent = "";
      dataForm.textContent = "";
    }
    if (dataForm.pdfContent.url) {
      // @ts-ignore
      dataForm.pdfContent = JSON.stringify(dataForm.pdfContent);
      // @ts-ignore
      dataForm.videoContent = "";
      dataForm.textContent = "";
    }
    if (dataForm.textContent) {
      // @ts-ignore
      dataForm.videoContent = "";
      // @ts-ignore
      dataForm.pdfContent = "";
    }
    if (dataForm.textType == 3) {
      // @ts-ignore
      dataForm.videoContent = "";
      // @ts-ignore
      dataForm.pdfContent = "";
      dataForm.textContent = "";
    }
    (!dataForm.id ? baseService.post : baseService.put)("/bus/busnotice", dataForm).then((res) => {
      ElMessage.success({
        message: t("prompt.success"),
        duration: 500,
        onClose: () => {
          visible.value = false;
          emit("refreshDataList");
        }
      });
    });
  });
};

defineExpose({
  init
});
</script>

<style lang="scss" scoped>
.myUEditorClass {
  :deep(.el-form-item__content) {
    width: calc(100% - 110px);
  }
}
</style>
